package com.advert.utils;


import com.advert.entity.MQTTClientStatusResp;
import com.advert.entity.PublishRespEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.FailureCallback;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.SuccessCallback;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
@Slf4j
public class RequestUtils {

    private AsyncRestTemplate asyncRestTemplate;

    private RestTemplate restTemplate;


    private String EMQX_AUTHORIZATION = "Basic YWRtaW46cHVibGlj";

    public RequestUtils() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10000);// 设置连接超时，单位毫秒
        requestFactory.setReadTimeout(10000);  //设置读取超时
        restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(requestFactory);
        log.info("RestTemplate初始化完成");
        asyncRestTemplate = new AsyncRestTemplate();
    }

    public ResponseEntity<String> post(String url, Map<String, Object> paramMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
        return restTemplate.postForEntity(url, httpEntity, String.class);
    }

    public ResponseEntity<PublishRespEntity> postPublish(String url, Map<String, Object> paramMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", EMQX_AUTHORIZATION);
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
        return restTemplate.postForEntity(url, httpEntity, PublishRespEntity.class);
    }

    public ResponseEntity<MQTTClientStatusResp> get(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", EMQX_AUTHORIZATION);
        HttpEntity<String> entity = new HttpEntity<String>("", headers);
       // log.info("请求的url:{}",url);
        return restTemplate.exchange(url, HttpMethod.GET, entity, MQTTClientStatusResp.class);
    }

    public ResponseEntity<String> getSubscriptionsResp(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", EMQX_AUTHORIZATION);
        HttpEntity<String> entity = new HttpEntity<String>("", headers);
        log.info("请求的url:{}",url);
        return restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    }


    // 异步请求
    public void postSync(String url, Map<String, Object> paramMap) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
            ListenableFuture<ResponseEntity<String>> entity = asyncRestTemplate.postForEntity(url, httpEntity, String.class);
            entity.addCallback(new SuccessCallback<ResponseEntity<String>>() {
                @Override
                public void onSuccess(ResponseEntity<String> result) {
                    log.info("请求url：{} 成功:{}", url, result.getStatusCode());
                }
            }, new FailureCallback() {
                @Override
                public void onFailure(Throwable ex) {
                    log.error("请求url：{} 失败:{}", url, ex.getMessage());
                    ex.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("请求url：{} 失败:{}", url, e.getMessage());
        }
    }

    // 异步请求
    public void postSyncRetry(String url, Map<String, Object> paramMap, int retry) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
            ListenableFuture<ResponseEntity<String>> entity = asyncRestTemplate.postForEntity(url, httpEntity, String.class);
            entity.addCallback(new SuccessCallback<ResponseEntity<String>>() {
                @Override
                public void onSuccess(ResponseEntity<String> result) {
                    HttpStatus statusCode = result.getStatusCode();
                    if (statusCode.value() == HttpStatus.OK.value()) {
                        log.info("请求url：{} ", url);
                    }
                }
            }, new FailureCallback() {
                @Override
                public void onFailure(Throwable ex) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("请求url：{} 失败:{}", url, e.getMessage());
        }
    }


}
